# -*- coding: utf-8 -*-

'''eof
name:申请企业未结清担保交易业务种类余额占比
code:EC112_EntUnsettledGuarantyBalanceRatio
tableName:
columnName:
groups:企业征信
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:申请企业未结清担保交易业务种类余额占比
eof'''

import json
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

# 获取表信息方法
def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

# 数值判断方法
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def EC112_EntUnsettledGuarantyBalanceRatio():
    try:
        data = EC_DSJ_2D['data']
        factor_key = {'01':'贷款担保',
                    '02':'票据承兑担保',
                    '03':'贸易融资担保',
                    '04':'项目融资担保',
                    '05':'信用证担保',
                    '06':'其他融资担保',
                    '10':'债券发行担保',
                    '07':'诉讼保全担保',
                    '08':'履约担保',
                    '09':'其他非融资担保',
                    '11':'再担保',
                    '12':'贷款保证保险',
                    '51':'信用证',
                    '61':'银行承兑汇票',
                    '62':'商业承兑汇票',
                    '71':'融资类银行保函',
                    '72':'非融资类银行保函'}
        flag = []
        # 信用提示信息
        EBA = getTable(data, 'EBA', 1, 1)
        if EBA == [{}]:
            TotalBalance =  u'缺失值'
        elif EBA == 0:
            TotalBalance = 0
        else:
            EB01 = getTable(EBA[0], 'EB01', 1, 0)
            if EB01 == 0:
                TotalBalance = 0
            elif EB01 == [{}]:
                TotalBalance = u'缺失值'
            else:
                #  信贷交易提示信息段
                EB01A = getTable(EB01[0], 'EB01A', 0, 1)
                if EB01A == 0:
                    TotalBalance = 0
                else:
                    EB01AJ05 = EB01A[0].get('EB01AJ05')
                    if isfloat(EB01AJ05) is False:
                        TotalBalance = u'缺失值'
                    else:
                        TotalBalance = float(EB01AJ05)
        # 明细汇总
        dict_bal = {'01':[0], '02':[0], '03':[0], '04':[0], '05':[0], '06':[0], '10':[0], '07':[0], '08':[0], '09':[0], '11':[0], '12':[0], '51':[0], '61':[0], '62':[0], '71':[0], '72':[0]}
        # 担保账户信息
        EDB = getTable(data, 'EDB', 1, 0)
        if EDB == [{}]:
            return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)
        elif EDB == 0:
            flag.append(0)
        else:
            # 担保账户信息明细单元
            ED04 = getTable(EDB[0], 'ED04', 0, 1)
            if ED04 == [{}]:
                return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)
            elif ED04 == 0:
                flag.append(0)
            else:
                for i in ED04:
                    try:
                        # 基本信息段
                        ED04A = getTable(i, 'ED04A', 1, 1)
                        # 在保责任信息段
                        ED04B = getTable(i, 'ED04B', 1, 1)
                        if ED04A == 0 or ED04B == 0:
                            flag.append(0)
                            continue
                        elif ED04A == [{}] or ED04A == [{}]:
                            flag.append(None)
                        else:
                            # 账户活动状态
                            ED04BD01 = ED04B[0].get('ED04BD01')
                            # 余额
                            ED04BJ01 = ED04B[0].get('ED04BJ01')
                            # 担保交易业务种类细分
                            ED04AD03 = ED04A[0].get('ED04AD03')
                            if ED04BD01 in null_type_list or ED04AD03 in null_type_list or isfloat(ED04BJ01) is False:
                                flag.append(None)
                            else:
                                flag.append(0)
                                if str(ED04BD01) == '1' and str(ED04AD03) in dict_bal.keys():
                                    dict_bal[str(ED04AD03)].append(float(ED04BJ01))
                                else:
                                    continue
                    except:
                        flag.append(None)
                        continue
        factorNotNone = list(filter(lambda x: x is not None, flag))
        if len(factorNotNone) == 0:
            return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)
        else:
            for key_i in list(dict_bal.keys()):
                dict_bal.update({factor_key[key_i]: sum(dict_bal[key_i])})
                dict_bal.pop(key_i)

            if TotalBalance == u"缺失值":
                dict_bal_ratio = u"缺失值"
            else:
                dict_bal_ratio = dict_bal.copy()
                if TotalBalance == 0:
                    for k in dict_bal_ratio.keys():
                        dict_bal_ratio.update({k: 0}) if dict_bal_ratio[k] == 0 else dict_bal_ratio.update({k: u"缺失值"})
                else:
                    for k in dict_bal_ratio.keys():
                        dict_bal_ratio.update({k: round(dict_bal[k]/TotalBalance, 4)})
            return json.dumps({'Dict_bal': dict_bal, 'Dict_bal_ratio': dict_bal_ratio}, ensure_ascii=False)
    except:
        return json.dumps({'Dict_bal': u"缺失值", 'Dict_bal_ratio': u"缺失值"}, ensure_ascii=False)


result = EC112_EntUnsettledGuarantyBalanceRatio()

